// 历史记录数据
var historyData = [
  {
    date: "2024-01-15",
    merchant: "蓝天科技公司",
    totalScore: 95,
    adminScore: 96,
    userScore: 94,
    count: 156,
    status: "正常",
  },
  {
    date: "2024-01-14",
    merchant: "绿洲购物中心",
    totalScore: 87,
    adminScore: 88,
    userScore: 86,
    count: 89,
    status: "需关注",
  },
  {
    date: "2024-01-13",
    merchant: "青山酒店集团",
    totalScore: 92,
    adminScore: 93,
    userScore: 91,
    count: 74,
    status: "正常",
  },
  {
    date: "2024-01-12",
    merchant: "白云物流中心",
    totalScore: 89,
    adminScore: 91,
    userScore: 87,
    count: 63,
    status: "需关注",
  },
  {
    date: "2024-01-11",
    merchant: "黄河旅行社",
    totalScore: 91,
    adminScore: 92,
    userScore: 90,
    count: 74,
    status: "正常",
  },
  {
    date: "2024-01-10",
    merchant: "长江汽车销售",
    totalScore: 87,
    adminScore: 89,
    userScore: 85,
    count: 52,
    status: "需关注",
  },
  {
    date: "2024-01-09",
    merchant: "紫峰建筑公司",
    totalScore: 92,
    adminScore: 93,
    userScore: 91,
    count: 82,
    status: "正常",
  },
  {
    date: "2024-01-08",
    merchant: "橙光教育机构",
    totalScore: 94,
    adminScore: 95,
    userScore: 93,
    count: 108,
    status: "正常",
  },
  {
    date: "2024-01-07",
    merchant: "赤阳娱乐场所",
    totalScore: 85,
    adminScore: 88,
    userScore: 82,
    count: 45,
    status: "需改进",
  },
  {
    date: "2024-01-06",
    merchant: "蓝天科技公司",
    totalScore: 95,
    adminScore: 96,
    userScore: 94,
    count: 156,
    status: "正常",
  },
];

// 初始化表格事件
function initTableEvents() {
  // 为查看按钮添加点击事件
  document
    .querySelectorAll("button[data-item]")
    .forEach(function (button) {
      button.addEventListener("click", function () {
        var item = JSON.parse(this.getAttribute("data-item"));
        showDetails(item);
      });
    });

  // 搜索功能
  var searchInput = document.querySelector(
    'input[placeholder="搜索记录..."]'
  );
  if (searchInput) {
    searchInput.addEventListener("input", function () {
      var searchTerm = this.value.toLowerCase();
      var filteredData = historyData.filter(function (item) {
        return (
          item.merchant.toLowerCase().includes(searchTerm) ||
          item.date.includes(searchTerm) ||
          item.status.toLowerCase().includes(searchTerm)
        );
      });
      updateTableData(filteredData);
    });
  }
}

// 更新表格数据（用于搜索和分页）
function updateTableData(data) {
  var tableBody = document.getElementById("history-table-body");
  tableBody.innerHTML = "";

  data.forEach(function (item) {
    var row = document.createElement("tr");
    row.className = "table-row-hover";

    // 根据状态设置不同的标签样式
    var statusClass = "";
    if (item.status === "正常") {
      statusClass = "bg-success/10 text-success";
    } else if (item.status === "需关注") {
      statusClass = "bg-warning/10 text-warning";
    } else if (item.status === "需改进") {
      statusClass = "bg-danger/10 text-danger";
    }

    // 根据分数设置颜色
    function getScoreClass(score) {
      return score >= 90
        ? "text-success"
        : score >= 85
        ? "text-warning"
        : "text-danger";
    }

    row.innerHTML =
      '<td class="px-6 py-4 text-neutral-700">' +
      item.date +
      "</td>" +
      '<td class="px-6 py-4 text-neutral-700">' +
      item.merchant +
      "</td>" +
      '<td class="px-6 py-4"><span class="font-medium ' +
      getScoreClass(item.totalScore) +
      '">' +
      item.totalScore +
      "</span></td>" +
      '<td class="px-6 py-4"><span class="font-medium ' +
      getScoreClass(item.adminScore) +
      '">' +
      item.adminScore +
      "</span></td>" +
      '<td class="px-6 py-4"><span class="font-medium ' +
      getScoreClass(item.userScore) +
      '">' +
      item.userScore +
      "</span></td>" +
      '<td class="px-6 py-4 text-neutral-700">' +
      item.count +
      "</td>" +
      '<td class="px-6 py-4"><span class="px-3 py-1 rounded-full text-sm font-medium ' +
      statusClass +
      '">' +
      item.status +
      "</span></td>" +
      '<td class="px-6 py-4"><button class="text-primary hover:text-primary/80 transition-colors duration-200" data-item=\'' +
      JSON.stringify(item) +
      "'>查看详情</button></td>";

    tableBody.appendChild(row);
  });

  // 重新绑定事件
  initTableEvents();
}

// 初始化模态框事件
function initModalEvents() {
  var modal = document.getElementById("detail-modal");
  var closeModal = document.getElementById("close-modal");
  var modalCloseBtn = document.getElementById("modal-close-btn");

  // 关闭模态框
  closeModal.addEventListener("click", function () {
    modal.classList.add("hidden");
    setTimeout(function () {
      modal.classList.remove("opacity-0");
      modal.querySelector("div").classList.remove("scale-100");
      modal.querySelector("div").classList.add("scale-95");
    }, 300);
  });

  // 模态框内的关闭按钮
  modalCloseBtn.addEventListener("click", function () {
    closeModal.click();
  });

  // 点击模态框外部关闭
  modal.addEventListener("click", function (e) {
    if (e.target === modal) {
      closeModal.click();
    }
  });

  // 按ESC键关闭
  document.addEventListener("keydown", function (e) {
    if (e.key === "Escape" && !modal.classList.contains("hidden")) {
      closeModal.click();
    }
  });
}

// 显示详情模态框
function showDetails(item) {
  var modal = document.getElementById("detail-modal");
  var modalDiv = modal.querySelector("div");

  // 更新模态框内容
  document.getElementById("modal-merchant-name").textContent =
    item.merchant;
  document.getElementById("modal-date").textContent = item.date;

  // 更新评分数据
  var totalScoreEl = document.getElementById("modal-total-score");
  var adminScoreEl = document.getElementById("modal-admin-score");
  var userScoreEl = document.getElementById("modal-user-score");

  totalScoreEl.textContent = item.totalScore;
  adminScoreEl.textContent = item.adminScore;
  userScoreEl.textContent = item.userScore;

  // 根据分数设置颜色
  function setScoreColor(element, score) {
    element.className =
      "text-3xl font-bold " +
      (score >= 90
        ? "text-success"
        : score >= 85
        ? "text-warning"
        : "text-danger");
  }

  setScoreColor(totalScoreEl, item.totalScore);
  setScoreColor(adminScoreEl, item.adminScore);
  setScoreColor(userScoreEl, item.userScore);

  // 更新评分人数
  document.getElementById("modal-count").textContent =
    item.count + "人参与评分";

  // 更新状态
  var statusEl = document.getElementById("modal-status");
  statusEl.textContent = item.status;
  statusEl.className =
    "px-3 py-1 rounded-full text-sm font-medium " +
    (item.status === "正常"
      ? "bg-success/10 text-success"
      : item.status === "需关注"
      ? "bg-warning/10 text-warning"
      : "bg-danger/10 text-danger");

  // 显示模态框
  modal.classList.remove("hidden");
  setTimeout(function () {
    modal.classList.add("opacity-100");
    modalDiv.classList.remove("scale-95");
    modalDiv.classList.add("scale-100");
  }, 10);

  // 初始化迷你图表
  setTimeout(function () {
    initMiniChart(item);
  }, 300);
}

// 初始化迷你图表
function initMiniChart(item) {
  var chartDom = document.getElementById("mini-chart");
  var miniChart = echarts.init(chartDom);
  var option = {
    tooltip: {
      trigger: "axis",
      formatter: "{b}: {c}分",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["前3日", "前2日", "前1日", "今日"],
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontSize: 10,
        color: "#4E5969",
      },
    },
    yAxis: {
      type: "value",
      min: Math.max(75, item.totalScore - 10),
      max: Math.min(100, item.totalScore + 5),
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: false,
      },
      splitLine: {
        show: false,
      },
    },
    series: [
      {
        name: "商户总分数",
        type: "line",
        data: [
          item.totalScore - 8,
          item.totalScore - 5,
          item.totalScore - 2,
          item.totalScore,
        ],
        smooth: true,
        symbol: "circle",
        symbolSize: 4,
        lineStyle: {
          width: 2,
          color: "#165DFF",
        },
        itemStyle: {
          color: "#165DFF",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(22, 93, 255, 0.2)",
            },
            {
              offset: 1,
              color: "rgba(22, 93, 255, 0)",
            },
          ]),
        },
      },
    ],
  };
  miniChart.setOption(option);

  // 监听窗口大小变化，调整迷你图表大小
  window.addEventListener("resize", function () {
    miniChart.resize();
  });
}
